package com.dtsz.m2.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.dtsz.m2.volley.httpUtil.interfase.HUCCallBackInterfase;
import com.dtsz.m2.volley.state.HUCState;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class FileUploadUtils {
    /**
     * @param url     请求地址这个大家都懂的
     * @param params  参数表单，采用的是map传入，请求的时候携带的参数在这里传入
     * @param files   上传的文件
     * @param handler
     * @return
     * @throws IOException
     */
    public static void post(HUCCallBackInterfase httpLogicAbst, int inputType, String url, Map<String, String> params, File files, Handler handler)
            throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString(); //ＵＵＩＤ是指在一台机器上生成的数字，它保证对在同一时空中的所有机器都是唯一的
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data"; //它会将表单的数据处理为一条消息，以标签为单元，用分隔符分开。既可以上传键值对，也可以上传文件
        String CHARSET = "UTF-8"; //编码格式
        long totalLength = 0;
        try {
            // 取得文件大小 这里一会显示上传进度条会用到
            totalLength = getFileSize(files);
            Log.d("lfq", "### size: " + totalLength);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long timeLong = System.currentTimeMillis();
        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); //用于配置默认的参数并返回HttpURLConnection
        conn.setReadTimeout(500000);//设置读取超时时长
        conn.setConnectTimeout(500000); // 设置连接超时时长
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setAllowUserInteraction(false); //是否允许用户交互
        conn.setChunkedStreamingMode(0);//分块编码，我这里不需要，因为要计算上传进度
        conn.setRequestMethod("POST");//上传方式
        conn.setRequestProperty("connection", "keep-alive"); //设置HttpURLConnection请求头里面的属性
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("sign", RSAEncrypt.md5Hander(timeLong));
        conn.setRequestProperty("timestamp", timeLong + "");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) { //表单的属性写入
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // 发送文件数据
        if (files != null) {
            StringBuilder sb1 = new StringBuilder();
            sb1.append(PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(LINEND);
            sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                    + files.getName() + "\"" + LINEND);
            sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
            sb1.append(LINEND);
            outStream.write(sb1.toString().getBytes());
            InputStream is = new FileInputStream(files);
            byte[] buffer = new byte[1024];
            int hasUpLoadCount = 0;
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
                hasUpLoadCount += len;
                int total = (int) (hasUpLoadCount * 100 / totalLength); //计算上传的进度
                Message msg = handler.obtainMessage();
                msg.what = HUCState.HUC_REQEUST_CODE_1;
                msg.arg1 = total;
                msg.sendToTarget();
                // ringProgressBar.setProgress(total); //设置进度条
            }
            is.close();
            outStream.write(LINEND.getBytes());
        }
        // 请求结束标志

        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 得到响应码
        int res = conn.getResponseCode();
        Log.d("lfq", "post: " + res);
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            int ch;
            while ((ch = in.read()) != -1) {
                sb2.append((char) ch);
            }
        }
        outStream.close();
        conn.disconnect();
        httpLogicAbst.onSuccessfulStrType(inputType, sb2.toString());
    }

    public static long getFileSize(File file) throws Exception {
        if (file == null) {
            return 0;
        }
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        return size;
    }

}
